﻿import { useSettingsStore } from "@/store";
import { ElementTypeEnum } from "@/enums";
import SensorAPI from "@/api/business/sensor.api";

export const useSensorStore = defineStore("sensor", () => {
  const settingsStore = useSettingsStore();
  // 工装-传感器信息（在工位的工装）
  const allTools = useStorage<ToolInfo[]>("toolSensorData", [] as ToolInfo[]);

  // 当前选中的工装/托盘
  const currentToolCode = useStorage<string>("currentToolCode", "");
  const currentToolCodeReadOnly = readonly(currentToolCode);
  const currentToolInfo = computed(() =>
    allTools.value.find((t) => t.toolCode === currentToolCode.value)
  );

  // 平台的待检传感器
  const pendingSensorData = ref<PendingSensor[]>([]);

  onMounted(() => {});

  /**
   * 添加工装
   * @param toolCode 工装编号
   */
  function addTool(toolCode: string) {
    if (allTools.value.some((t) => t.toolCode === toolCode)) {
      ElMessage.warning("工装已存在");
      return;
    }
    allTools.value.push({ toolCode, toolName: "", stationNum: null, sensors: [] });
  }

  /**
   * 删除工装，绑定的传感器也会删除
   * @param toolCode 工装编号
   */
  function delTool(toolCode: string) {
    const delIndex = allTools.value.findIndex((t) => t.toolCode === toolCode);
    allTools.value.splice(delIndex, 1);
  }

  /**
   * 工装绑定工位，之前绑定的会先解除
   * @param toolCode
   * @param stationNum
   */
  function bindToolAndStation(toolCode: string, stationNum: number) {
    // 先解绑
    allTools.value.forEach((t) => {
      if (t.stationNum == stationNum) t.stationNum = null;
    });
    // 再绑定
    allTools.value.find((t) => t.toolCode == toolCode).stationNum = stationNum;
  }

  /**
   * 工位移除工装
   * @param stationNum
   */
  function stationRemoveTool(stationNum: number) {
    allTools.value.forEach((t) => {
      if (t.stationNum == stationNum) t.stationNum = null;
    });
  }

  // 请求平台接口，获取传感器数据，并给isSelected赋值
  function loadSensorData(param: { sensorCode: string; startDate?: string; endDate?: string }) {
    SensorAPI.getPendingSensors(param).then((res) => {
      pendingSensorData.value.length = 0;
      const allExistCodes = allTools.value.flatMap((t) => t.sensors.map((s) => s.sensorCode));
      for (const sensor of res) {
        sensor.isSelected = allExistCodes.some((s) => s === sensor.sensorCode);
        pendingSensorData.value.push(sensor);
      }
    });
  }

  // 判断传感器是否已添加
  function isAlreadySelected(sensorCode: string) {
    const allExistCodes = allTools.value.flatMap((t) => t.sensors.map((s) => s.sensorCode));
    if (allExistCodes.some((s) => s === sensorCode)) {
      return true;
    } else return false;
  }

  // 设置当前工装/托盘
  function setCurrentTool(toolCode: string) {
    currentToolCode.value = toolCode;
  }
  // 添加已选择的传感器
  function addSelectedSensors(sensors: SensorInfo[] | SensorInfo) {
    if (settingsStore.elementType !== ElementTypeEnum.Rain && !currentToolCode.value) {
      ElMessage.warning("请先选择工装/托盘");
      return;
    }
    const sensorArray = Array.isArray(sensors) ? sensors : [sensors];
    const existCodes = [];
    const allExistCodes = allTools.value.flatMap((t) => t.sensors.map((s) => s.sensorCode));

    // 向已选择的传感器列表中添加，如果已存在则不添加
    for (const sensor of sensorArray) {
      if (!allExistCodes.some((s) => s === sensor.sensorCode)) {
        currentToolInfo.value.sensors.push(sensor);
        // 修改待检传感器 为已添加
        const pendingSensor = pendingSensorData.value.find(
          (s) => s.sensorCode === sensor.sensorCode
        );
        if (pendingSensor) pendingSensor.isSelected = true;
      } else existCodes.push(sensor.sensorCode);
    }
    // 重新排序
    currentToolInfo.value.sensors.sort((x, y) => x.slotNum - y.slotNum);
    if (existCodes.length > 0) ElMessage.warning(`已存在传感器：${existCodes.join(",")}`);
  }

  /**
   * 移除已选择的传感器
   * @param sensorCodes null: 移除传感器；
   */
  function removeSelectedSensors(sensorCodes?: string[] | string) {
    if (settingsStore.elementType !== ElementTypeEnum.Rain && !currentToolCode.value) {
      ElMessage.warning("请先选择工装/托盘");
      return;
    }

    // 统一转换为数组处理
    const sensorArray =
      sensorCodes == null
        ? currentToolInfo.value.sensors.map((sensor) => sensor.sensorCode)
        : Array.isArray(sensorCodes)
          ? sensorCodes
          : [sensorCodes];
    for (const code of sensorArray) {
      for (const tool of allTools.value) {
        const index = tool.sensors.findIndex((s) => s.sensorCode === code);
        if (index >= 0) tool.sensors.splice(index, 1);
        // 修改待检传感器 为未添加
        const pendingSensor = pendingSensorData.value.find((s) => s.sensorCode === code);
        if (pendingSensor) pendingSensor.isSelected = false;
      }
    }
  }

  return {
    allTools,
    currentToolCode: currentToolCodeReadOnly,
    currentToolInfo,
    pendingSensorData,

    addTool,
    delTool,
    bindToolAndStation,
    stationRemoveTool,

    isAlreadySelected,
    loadSensorData,
    setCurrentTool,
    addSelectedSensors,
    removeSelectedSensors,
  };
});
